﻿using System;
using System.Data;
using System.Data.Common;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Xoohoo.Infrastructure.FastReflectionLib;

namespace Xoohoo.Extensions
{
    public static class DatabaseExtensions
    {
        public static int? ExecuteScalarInt(this Database db, DbCommand command)
        {
            object o = db.ExecuteScalar(command);
            return convert(o);
        }
        public static int? ExecuteScalarInt(this Database db, CommandType commandType, string commandText)
        {
            object o = db.ExecuteScalar(commandType, commandText);
            return convert(o);
        }
        public static int? ExecuteScalarInt(this Database db, DbCommand command, DbTransaction transaction)
        {
            object o = db.ExecuteScalar(command, transaction);
            return convert(o);
        }
        public static int? ExecuteScalarInt(this Database db, string storedProcedureName, params object[] parameterValues)
        {
            object o = db.ExecuteScalar(storedProcedureName, parameterValues);
            return convert(o);
        }
        public static int? ExecuteScalarInt(this Database db, DbTransaction transaction, CommandType commandType, string commandText)
        {
            object o = db.ExecuteScalar(transaction, commandType, commandText);
            return convert(o);
        }
        public static int? ExecuteScalarInt(this Database db, DbTransaction transaction, string storedProcedureName, params object[] parameterValues)
        {
            object o = db.ExecuteScalar(transaction, storedProcedureName, parameterValues);
            return convert(o);
        }
        private static int? convert(object o)
        {
            if (o == null || o is DBNull) return null;
            try
            {
                return Convert.ToInt32(o);
            }
            catch
            {
                return null;
            }
        }

    }
}
